﻿using Microsoft.AspNetCore.Mvc.Filters;
using System.Security.Claims;

namespace OpenAI.WebAPI.Filters
{
    public class InitFilter : IAsyncActionFilter
    {
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            if (Guid.TryParse(context.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier), out Guid id)) 
            {
                var appUserProp = context.Controller.GetType().GetProperty("AppUserId");
                appUserProp.SetValue(context.Controller, id);
            }
            
            await next();
        }
    }
}
